package com.longtime.aliyun.ocr;

import com.aliyun.teaopenapi.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teaopenapi.models.Params;
import com.longtime.aliyun.ocr.properties.AliyunOcrParamsProperties;
import com.longtime.aliyun.ocr.properties.AliyunOcrProperties;
import com.longtime.aliyun.ocr.service.impl.AliyunOcrService;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author xhc
 * @version 1
 * @date 2025-05-26 12:59:55
 * @description 阿里云OCR自动配置类
 */
@Configuration
@EnableConfigurationProperties({AliyunOcrProperties.class, AliyunOcrParamsProperties.class})
@ConditionalOnProperty(
        prefix = "com.longtime.aliyun.ocr",
        name = "enabled",
        havingValue = "true",
        matchIfMissing = true)
@ConditionalOnClass(AliyunOcrService.class)
public class AliyunOcrAutoConfiguration {

    @Resource
    private AliyunOcrProperties properties;

    @Resource
    private AliyunOcrParamsProperties paramsProperties;

    @Bean
    @ConditionalOnMissingBean
    public Client ocrClient() {
        try {
            com.aliyun.credentials.Client credential = new com.aliyun.credentials.Client();
            Config config = new Config()
                    .setCredential(credential)
                    .setEndpoint(properties.getEndpoint());
            return new Client(config);
        } catch (Exception e) {
            throw new BeanCreationException("初始化Bean失败：com.aliyun.teaopenapi.Client");
        }
    }

    @Bean
    @ConditionalOnMissingBean
    public Params params() {
        return new Params()
                .setAction(paramsProperties.getAction())
                .setVersion(paramsProperties.getVersion())
                .setProtocol(paramsProperties.getProtocol())
                .setMethod(paramsProperties.getMethod())
                .setAuthType(paramsProperties.getAuthType())
                .setStyle(paramsProperties.getStyle())
                .setPathname(paramsProperties.getPathName())
                .setReqBodyType(paramsProperties.getReqBodyType())
                .setBodyType(paramsProperties.getBodyType());
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnBean({Client.class, Params.class})
    public AliyunOcrService aliyunOcrService() {
        return new AliyunOcrService();
    }

}
